/**
 * 英雄类
 */

 export default class Hero extends Laya.Script {


    constructor() { super() }

    private sprite: Laya.Sprite

    private drag: boolean = false // 是否在拖动

    public level: number = 1 // 等级

    public index: number = 0 // 在第几个平台

    onEnable(): void {

        this.sprite = this.owner as Laya.Sprite

        this.sprite.on(Laya.Event.MOUSE_DOWN, this, this.mouseDown)
        Laya.stage.on(Laya.Event.MOUSE_MOVE, this, this.mouseMove)
        this.sprite.on(Laya.Event.MOUSE_UP, this, this.mouseUp)
    }

    onDisable(): void {
        Laya.Pool.recoverByClass(Hero)
    }

    private mouseDown(event: Laya.Event): void {
        this.drag = true
        let max = 0 // 置于最顶层
        if (this.sprite.parent['_children']) {
            this.sprite.parent['_children'].forEach(e => {
                let i = this.sprite.parent.getChildIndex(e)
                if (i > max) max = i
            })
        }
        this.sprite.parent.setChildIndex(this.sprite, max)
    }

    private mouseMove(event: Laya.Event): void {
        if (this.drag) {
            this.sprite.x = event.stageX - this.sprite.width / 2
            this.sprite.y = event.stageY - this.sprite.height / 2
        }
    }

    private mouseUp(event: Laya.Event): void {
            this.drag = false
            Laya.stage.event('drag_end', this.owner)
    }

    // 设置等级
    public setLevel(level: number): void {
        this.level = level
        this.sprite.loadImage('images/level_'+level+'.png')
    }

    // 设置位置
    public setPosition(x:number, y:number): void {
        this.sprite.x = x
        this.sprite.y = y
    }

    // 设置在平台得位置
    public setIndex(index: number, plat: Laya.Sprite): void {
        this.index = index
        this.setPosition(
            plat.x + plat.width / 2 - this.sprite.width / 2,
            plat.y + plat.height / 2 - this.sprite.height
        )
    }

 }